import json

from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from django.views import View
from django.http import JsonResponse
from django.contrib.auth import logout
from django.conf import settings
import qiniu

from lovehome_pro.libs.qiniuyun.qiniu_storage import storage
from lovehome_pro.utils.Loginmixin import LoginMixin
from six_it.uitls import get_FileSize, timenum
from xyuzi.models import House, User, Order
from django_redis import get_redis_connection


class JpgView(LoginMixin,View):
    def post(self,request):
        file = request.FILES.get('avatar')
        if not file:
            return JsonResponse({
                'errno': '400',
                'errmsg': '缺少图片数据'
            })
        f = get_FileSize(file)
        token = storage(f)
        url = "http://qa77xtdyw.bkt.clouddn.com/"
        image = url + token
        data = {}
        data['avatar_url'] = image
        try:
             User.objects.filter(id=request.user.id).update(avatar=token)
        except Exception as e:
            return JsonResponse({
                'errno':'400',
                'errmsg':'数据库出错'
            })
        return JsonResponse({
            'data':data,
            'errno':'0',
            'errmsg':'上传大头像成功',
        })

class MyhouslistView(LoginMixin,View):
    def get(self,request):
        try:
            user = House.objects.filter(user=request.user)
        except Exception as e:
            return JsonResponse({
                'errno':'400',
                'errmsg':'数据库出错'
            })
        addersses_list = []
        url = "http://qa77xtdyw.bkt.clouddn.com/"
        ctime = timezone.localtime().strftime('%Y%m%d%H%M%S')
        for add in user:
            address_dict = {
                'house_id':add.id,
                'order_count':add.order_count,
                'title':add.title,
                'ctime':add.create_time,
                'price':add.price,
                'area_name':add.area.name,
                'address':add.address,
                'room_count':add.room_count,
                'img_urls':url + str(add.index_image_url),
                'user_avatar':url  +  str(add.user.avatar)

            }
            addersses_list.append(address_dict)
        data ={}
        data['houses'] = addersses_list
        return JsonResponse({
            'data':data,
            'errmsg':'ok',
            'errno':'0'
        })

class HouseOrdeView(LoginMixin,View):
    def post(self,request):
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')
        if not all([house_id,start_date,end_date]):
            return JsonResponse({
                'errno':'400',
                'errmsg':'缺少必传参数'
            })
        day = timenum(end_date,start_date)
        try:
            house= House.objects.get(id=house_id)
            house.order_count += 1
            house.save()
            house_price = house.price

            order = Order.objects.create(
                user=request.user,
                house_id=house_id,
                begin_date=start_date,
                end_date=end_date,
                days=day,
                house_price=house_price ,
                amount=house_price * day,
                status=Order.ORDER_STATUS.get('WAIT_ACCEPT')

            )
        except Exception as e:
            return JsonResponse({
                'errno':'400',
                'errmsg':'添加数据库出错'
            })
        order_id = order.id
        data = {}
        data['order_id'] = order_id
        return JsonResponse({
            'data':data,
            'errno':'0',
            'errmsg':'ok'
        })


    def get(self, request):
        role =request.GET.get("role")

        if role == 'custom':
            data = {}
            orders_list = []
            try:
                orders = Order.objects.filter(user_id=request.user.id)
                # Order.objects.filter(user_id=3)
            except Exception as e:
                return JsonResponse({
                    'errno': '400',
                    'errmsg': '数据库出错'
                })
            url = "http://qa77xtdyw.bkt.clouddn.com/"

            for order in orders:
                orders_dict = {
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.create_time,
                    "days": order.days,
                    "end_date": order.end_date,
                    "img_url": url + str(order.house.index_image_url),
                    "order_id": order.id,
                    "start_date": order.begin_date,
                    "status": Order.ORDER_STATUS_ENUM.get(order.status, 'WAIT_COMMENT'),
                    "title": order.house.title,
                }
                orders_list.append(orders_dict)

            data["orders"] = orders_list

            return JsonResponse({
                'data': data,
                'errmsg': 'ok',
                'errno': '0'
            })

        if role == 'landlord':
            data = {}
            orders_list = []
            try:
                houses = House.objects.filter(user_id=request.user.id)
                orders = Order.objects.filter(house_id__in=[house.id for house in houses])
                # Order.objects.filter(user_id=3)
            except Exception as e:
                return JsonResponse({
                    'errno': '400',
                    'errmsg': '数据库出错'
                })
            url = "http://qa77xtdyw.bkt.clouddn.com/"


            for order in orders:
                orders_dict = {
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.create_time,
                    "days": order.days,
                    "end_date": order.end_date,
                    "img_url": url + str(order.house.index_image_url),
                    "order_id": order.id,
                    "start_date": order.begin_date,
                    "status": Order.ORDER_STATUS_ENUM.get(order.status, 0),
                    "title": order.house.title,
                }
                orders_list.append(orders_dict)

            data["orders"] = orders_list

            return JsonResponse({
                'data': data,
                'errmsg': 'ok',
                'errno': '0'
            })


class OrderCommView(View):
    def put(self,request,order_id):
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get('comment')
        if not all([comment,order_id]):
            return JsonResponse({
                'errno':'400',
                'errmsg':'缺少参数'
            })

        try:
            order = Order.objects.filter(id=order_id).update(comment=comment,status=Order.ORDER_STATUS.get("COMPLETE"))
        except Exception as e:
            return JsonResponse({
                'errno':'400',
                'errmsg':'保存出错'
            })
        return JsonResponse({
            'errno':'0',
            'errmsg':'评论成功'
        })
